package com.iot.compont;

import com.iot.gateway.GatewayEntity;
import org.springframework.stereotype.Component;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Administrator
 */
@Component
public class NetworkInstance {
    private ConcurrentHashMap<String, ArrayBlockingQueue<GatewayEntity>> networkConcurrentHashMap = new ConcurrentHashMap<>();

    public Boolean putMap(String networkType, GatewayEntity gateway) {

        ArrayBlockingQueue<GatewayEntity> queue = networkConcurrentHashMap.computeIfAbsent(
                networkType,
                k -> new ArrayBlockingQueue<>(100) // 指定队列容量为100，可根据需要调整
        );
        return queue.offer(gateway);
    }

    public void deleteMap(String networkType, GatewayEntity gateway) {
        ArrayBlockingQueue<GatewayEntity> queue = networkConcurrentHashMap.get(networkType);
        if (queue == null) {
            return; // 如果队列不存在，返回 false
        }
        // 创建一个临时队列用于存储未被删除的元素
        ArrayBlockingQueue<GatewayEntity> tempQueue = new ArrayBlockingQueue<>(queue.remainingCapacity() + queue.size());
        while (!queue.isEmpty()) {
            GatewayEntity entity = queue.poll(); // 从原队列中取出元素
            if (!entity.getId().equals(gateway.getId())) {
                tempQueue.offer(entity); // 将未被删除的元素放入临时队列
            }
        }
        // 将临时队列中的元素重新放回原队列
        while (!tempQueue.isEmpty()) {
            queue.offer(tempQueue.poll());
        }

    }
}
